/*
 * Login.java
 *
 * Created on Jan 15, 2011, 1:18:36 PM
 */
package edu.rit.varapp.graphical;

import edu.rit.varapp.utilities.CleanupThread;
import edu.rit.varapp.datalayer.Connect;
import edu.rit.varapp.datalayer.Encryptor;
import edu.rit.varapp.db.DatabaseConnection;
import edu.rit.varapp.logging.Logging;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 * Login is the entry point to the VAR application for a non-admin. It allows the client to connect to the database
 * using their email and password, or register their email and password (for new users).
 * @author Eric Kisner
 */
public class Login extends javax.swing.JFrame {

    private final Connect connector = new Connect( DatabaseConnection.instance() );

    /** Creates new form Login */
    public Login() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings( "unchecked" )
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jLabel1 = new javax.swing.JLabel();
        emailField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        passwordField = new javax.swing.JPasswordField();
        jPanel1 = new javax.swing.JPanel();
        loginButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        registerButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(400, 150));
        setResizable(false);

        jLabel1.setText("Email:");

        jLabel2.setText("Password:");

        jPanel1.setLayout(new java.awt.GridBagLayout());

        loginButton.setText("Login");
        loginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 24, 0);
        jPanel1.add(loginButton, gridBagConstraints);

        jLabel3.setText("To register a new email and password");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 9;
        jPanel1.add(jLabel3, gridBagConstraints);

        registerButton.setText("Register");
        registerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                registerButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 10;
        jPanel1.add(registerButton, gridBagConstraints);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(emailField, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(emailField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
        String email = emailField.getText();
        String password = getPassword();
        int entityId = -1;
        try {
            entityId = connector.loginClient( email, password );
        } catch( SQLException sqle ) {
            Logging.log( "There was an error when trying to log the "
                         + "client into the application: " + sqle.getMessage(), this.getClass() );
        }
        if( entityId == -1 ) {
            JOptionPane.showMessageDialog( rootPane, "Incorrect email/password combination, please try again." );
            return;
        } else {
            new CustomerOperations( entityId ).setVisible( true );
            this.dispose();
        }
    }//GEN-LAST:event_loginButtonActionPerformed

    private void registerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_registerButtonActionPerformed
        this.setEnabled( false );
        new Register( this, connector ).setVisible( true );
    }//GEN-LAST:event_registerButtonActionPerformed

    /**
     * This method returns the entered text in the password field. For additional security, it is recommended to
     * set each character from the returned password text to 0 once retrieved.
     * @return The hashed password that was entered by the user.
     */
    private String getPassword() {
        char[] pwdText = passwordField.getPassword();
        String password = Encryptor.computeHash( new String( pwdText ) );
        for( int i = 0; i < pwdText.length; i++ ) {
            pwdText[i] = 0;
        }
        return password;
    }

    /**
     * @param args the command line arguments
     */
    public static void main( String args[] ) {
        java.awt.EventQueue.invokeLater( new Runnable() {

            public void run() {
                new Login().setVisible( true );
            }
        } );

        Runtime.getRuntime().addShutdownHook( new CleanupThread() );
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField emailField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton loginButton;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JButton registerButton;
    // End of variables declaration//GEN-END:variables
}
